<template>
  <div class="add-friend-page">
    <el-row>
      <el-col :span="8">
        <el-card class="users-list">
          <el-button icon="back" @click="addFriend">返回</el-button>
          <div slot="header" class="clearfix">
            <span>所有用户</span>
          </div>
          <el-menu class="el-menu-vertical-demo">
            <el-menu-item v-for="user in users" :key="user.id" @click="chatWithUser(user)">
              <el-avatar :src="user.avatar" />
              <span class="user-name">{{ user.name }}</span>
              <el-button type="text" @click.stop="sendMessage(user)">发消息</el-button>
            </el-menu-item>
          </el-menu>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card class="chat-box" v-if="currentUser">
          <div slot="header" class="clearfix">
            <span>{{ currentUser.name }}</span>
            <el-button @click="addFriend">添加好友</el-button>
          </div>
          <div class="messages">
            <div v-for="message in messages" :key="message.id" :class="{'message': true, 'self-message': message.self}">
              <el-avatar :src="message.avatar" :class="{'self-avatar': message.self}" />
              <div class="message-content">
                <span class="message-username">{{ message.username }}</span>
                <p v-if="!message.image">{{ message.content }}</p>
                <img v-if="message.image" :src="message.image" alt="uploaded image" class="uploaded-image"/>
                <span class="message-time">{{ message.time }}</span>
              </div>
            </div>
          </div>
          <div class="input-area">
            <el-input v-model="newMessage" placeholder="输入消息..." @keyup.enter="sendMessage">
              <template #append>
                <el-button @click="sendMessage">发送</el-button>
              </template>
            </el-input>
            <el-upload
              class="upload-demo"
              action="https://jsonplaceholder.typicode.com/posts/"
              :on-success="handleUploadSuccess"
              :file-list="fileList"
              list-type="picture"
              :show-file-list="false">
              <el-button icon="el-icon-upload" class="upload-button">上传图片</el-button>
            </el-upload>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      users: [
        { id: 1, name: 'wulong', avatar: 'src/assets/images/wl.png' },
      ],
      currentUser: null,
      messages: [],
      newMessage: '',
      fileList: [],
      responses: {
        "你好": "你好!",
        "天气": "今天的天气很好，适合出去走走。",
        "再见": "再见，希望很快再见到你！",
        // 添加更多的消息-回复对
        // ...
      }
    };
  },
  methods: {
    chatWithUser(user) {
      this.currentUser = user;
      this.messages = [
        // Fetch messages with this user from server
      ];
    },
    sendMessage() {
      if (this.newMessage.trim() === '') return;

      // Add the user's message
      this.messages.push({
        id: Date.now(),
        username: 'User', // Replace with actual user name
        avatar: 'src/assets/images/wl.png', // Replace with actual user avatar
        content: this.newMessage,
        time: new Date().toLocaleString(),
        self: true,
      });

      // Store the sent message for reply context
      const sentMessage = this.newMessage;

      // Clear the input field
      this.newMessage = '';

      // Simulate a reply from the current user
      setTimeout(() => {
        this.messages.push({
          id: Date.now() + 1,
          username: this.currentUser.name,
          avatar: this.currentUser.avatar,
          content: this.generateReply(sentMessage),
          time: new Date().toLocaleString(),
          self: false,
        });
      }, Math.random() * 5000 + 2000); // Random delay between 2 to 7 seconds
    },
    handleUploadSuccess(response, file) {
      this.messages.push({
        id: Date.now(),
        username: 'YourName', // Replace with actual user name
        avatar: 'https://example.com/your-avatar.jpg', // Replace with actual user avatar
        image: URL.createObjectURL(file.raw),
        time: new Date().toLocaleString(),
        self: true,
      });

      // Simulate a reply from the current user
      setTimeout(() => {
        this.messages.push({
          id: Date.now() + 1,
          username: this.currentUser.name,
          avatar: this.currentUser.avatar,
          content: '这是自动回复的消息。',
          time: new Date().toLocaleString(),
          self: false,
        });
      }, Math.random() * 5000 + 2000); // Random delay between 2 to 7 seconds
    },
    generateReply(sentMessage) {
      const closestMatch = this.getClosestMatch(sentMessage, Object.keys(this.responses));
      return this.responses[closestMatch] || '谢谢你的消息！';
    },
    getClosestMatch(input, possibleMatches) {
      let closestMatch = '';
      let closestDistance = Infinity;

      possibleMatches.forEach(match => {
        const distance = this.levenshteinDistance(input, match);
        if (distance < closestDistance) {
          closestDistance = distance;
          closestMatch = match;
        }
      });

      return closestMatch;
    },
    levenshteinDistance(a, b) {
      const an = a ? a.length : 0;
      const bn = b ? b.length : 0;
      if (an === 0) return bn;
      if (bn === 0) return an;

      const matrix = new Array(an + 1);
      for (let i = 0; i <= an; i++) {
        matrix[i] = new Array(bn + 1);
        matrix[i][0] = i;
      }
      for (let j = 0; j <= bn; j++) {
        matrix[0][j] = j;
      }

      for (let i = 1; i <= an; i++) {
        for (let j = 1; j <= bn; j++) {
          const cost = a[i - 1] === b[j - 1] ? 0 : 1;
          matrix[i][j] = Math.min(
            matrix[i - 1][j] + 1, // deletion
            matrix[i][j - 1] + 1, // insertion
            matrix[i - 1][j - 1] + cost // substitution
          );
        }
      }

      return matrix[an][bn];
    },
    addFriend() {
      this.$router.push('/social/friends');
    },
  },
};
</script>

<style scoped>
.add-friend-page {
  padding: 20px;
}

.users-list {
  height: 100%;
  overflow-y: auto;
}

.user-name {
  margin-left: 10px;
}

.chat-box {
  height: 100%;
}

.messages {
  height: 400px;
  overflow-y: auto;
  padding: 10px;
  background-color: #f5f5f5;
}

.message {
  display: flex;
  margin-bottom: 10px;
}

.self-message {
  justify-content: flex-end;
  text-align: right;
}

.self-message .message-content {
  margin-right: 10px;
}

.message-content {
  margin-left: 10px;
}

.message-username {
  font-weight: bold;
}

.message-time {
  font-size: 12px;
  color: #888;
  margin-top: 5px;
}

.uploaded-image {
  max-width: 100px;
  max-height: 100px;
}

.input-area {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.upload-button {
  margin-left: 10px;
}

.self-avatar {
  order: 2;
}
</style>
